//
//  MYGAllIncientViewController.swift
//  MYGrow
//
//  Created by Mo on 2024/3/12.
//

import UIKit
import JXPagingView
import JXSegmentedView

class MYGAllIncientViewController: MYGBaseController {
    private var selectBtn:UIButton!
    private var gradientLayer:CAGradientLayer!
    private var sectionArr:Array<MYGScheduleModel> = []
    private var finishArr:[MYGScheduleListModel] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        getAllSchedules()
        NotificationCenter.default.addObserver(self, selector: #selector(getAllSchedules), name: NSNotification.Name.init("MYGScheduleRefresh"), object: nil)

    }
    func initUI() {
        view.addSubview(scheduleTable)
        scheduleTable.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview()
        }
    }
    @objc func getAllSchedules(){
        MMYGNetwork<MYGScheduleAPI, MYGScheduleBaseModel>.request(target: .scheduleList(params: ["doctor_id":MYGUserManager.user?.doctor.id ?? 0])) {[weak self] result in
            self?.sectionArr.removeAll()
            self?.finishArr.removeAll()
            let mode:MYGScheduleBaseModel = result ?? MYGScheduleBaseModel()
            self?.sectionArr = mode.data
            if self?.sectionArr.count ?? 0 > 0{
                for ind in 0...(self?.sectionArr.count)! - 1{
                    let arr:[MYGScheduleListModel] = self?.sectionArr[ind].lists ?? []
                    var newArr:[MYGScheduleListModel] = []
                    for sec in 0...arr.count - 1 {
                        let mod:MYGScheduleListModel = arr[sec]
                        if mod.schedule_status == 3 {
                            self?.finishArr.append(mod)
                        }else{
                            newArr.append(mod)
                        }
                    }
                    let mo:MYGScheduleModel = (self?.sectionArr[ind])!
                    mo.lists = newArr
                    self?.sectionArr[ind] = mo
                }
                var newSectionArr:[MYGScheduleModel] = []
                
                for ind in 0...(self?.sectionArr.count)! - 1{
                    let mode:MYGScheduleModel = self?.sectionArr[ind] ?? MYGScheduleModel()
                    if mode.lists.count > 0{
                        newSectionArr.append(mode)
                    }
                }
                self?.sectionArr = newSectionArr
            }
            self?.scheduleTable.reloadData()
            MYGLoading.hide()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    private lazy var scheduleTable: UITableView = {
        let cont = UITableView(frame: CGRectZero, style: .grouped)
        cont.delegate = self
        cont.dataSource = self
        cont.separatorStyle = .none
        cont.backgroundColor = .rgba(240, 240, 240)
        cont.allowsMultipleSelectionDuringEditing = true
        return cont
    }()
    override var hideNavigationController: Bool {
        true
    }
    //渐变色背景
    func insertselectGradLayer(vi:UIView) {
        vi.layoutIfNeeded()
        gradientLayer = CAGradientLayer()
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0)
        gradientLayer.frame = CGRect(x: 0, y: 0, width: 56, height: 30)
        gradientLayer.colors = [RGBA(r: 202, g: 172, b: 255, a: 1).cgColor,RGBA(r:143,g:134,b:255,a:1).cgColor]
        vi.layer.insertSublayer(gradientLayer, at: 0)
    }
}
extension MYGAllIncientViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        let sche:MYGScheduleModel = sectionArr[section]
//        return sche.lists.count
        if section < sectionArr.count{
            let sche:MYGScheduleModel = sectionArr[section]
            return sche.lists.count
        }else{
            return finishArr.count
        }
//        return 3
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return sectionArr.count + 1
//        return 2
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 120
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerV = UIView()
        view.backgroundColor = .clear
        let titleL = UILabel()
//        titleL.text = "222"
        if section < sectionArr.count{
            let sche:MYGScheduleModel = sectionArr[section]
            titleL.text = sche.year
        }else{
            titleL.text = "已完成"
        }
        titleL.font = .medium(17)
        titleL.textColor = .rgba(34, 34, 34)
        headerV.addSubview(titleL)
        titleL.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
            make.height.equalTo(24)
        }
        return headerV
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section < sectionArr.count{
            let cell = MYGScheduleTableViewCell(style: .default, reuseIdentifier: "MYGScheduleTableViewCell")
            cell.selectionStyle = .none
            let sche:MYGScheduleModel = sectionArr[indexPath.section]
            let scheDetail:MYGScheduleListModel = sche.lists[indexPath.row]
            cell.model = scheDetail
            cell.selectBlock = {[weak self] in
                self?.changeStatus(str: "\(scheDetail.id)")
            }
            return cell
        }else{
            let cell = MYGScheduleTableViewCell(style: .default, reuseIdentifier: "MYGScheduleTableViewCell")
            cell.selectionStyle = .none
            let scheDetail:MYGScheduleListModel = finishArr[indexPath.row]
            cell.model = scheDetail
            cell.selectBlock = {[weak self] in
                self?.changeStatus(str: "\(scheDetail.id)")
            }
            return cell
        }

    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section < sectionArr.count{
            let vc = MYGScheduleDetailViewController()
            let sche:MYGScheduleModel = sectionArr[indexPath.section]
            let scheDetail:MYGScheduleListModel = sche.lists[indexPath.row]
            vc.scheModel = scheDetail
            self.navigationController?.pushViewController(vc)
        }else{
            let vc = MYGScheduleDetailViewController()
            let scheDetail:MYGScheduleListModel = finishArr[indexPath.row]
            vc.scheModel = scheDetail
            self.navigationController?.pushViewController(vc)
        }

    }
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let unbind = UIContextualAction(style: .normal, title: "删除") {[weak self]
            (action, view, completionHandler) in
            guard let `self` = self else {return}
            var idStr:String = ""
            if indexPath.section < sectionArr.count{
                let sche:MYGScheduleModel = sectionArr[indexPath.section]
                let scheDetail:MYGScheduleListModel = sche.lists[indexPath.row]
                idStr = "\(scheDetail.id)"
            }else{
                let scheDetail:MYGScheduleListModel = finishArr[indexPath.row]
                idStr = "\(scheDetail.id)"
            }
            MYGLoading.show()
            MMYGNetwork<MYGScheduleAPI, MYGEmptyModel>.request(target: .deleteSche(param: idStr)) {[weak self] result in
                self!.getAllSchedules()
                MYGLoading.hide()
            } failed: { _, error in
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }

            completionHandler(true)
        }
        unbind.backgroundColor = UIColor.init(hexString: "#FF0000")
        
        let configuration = UISwipeActionsConfiguration(actions: [unbind])
        return configuration
    }
    private func changeStatus(str:String){
        MYGLoading.show()
        MYGNetwork<MYGScheduleAPI, MYGEmptyModel>.request(target: .changeScheduleStatue(param: str)) {[weak self] result in
            MYGLoading.hide()
            self?.getAllSchedules()
        } failed: { _, error in
            MYGLoading.hide()
        }
    }
}
extension MYGAllIncientViewController: JXSegmentedListContainerViewListDelegate {
    
    func listView() -> UIView {
        view
    }
}
